package com.example.demo.controller;

import com.example.demo.dto.ApiResponse;
import com.example.demo.dto.RegisterRequest;
import com.example.demo.service.AuthService;
import com.example.demo.service.TokenBlacklistService;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/auth")
@RequiredArgsConstructor
public class AuthController {

    private final AuthService authService;
    private final TokenBlacklistService tokenBlacklistService;

    @PostMapping("/register")
    public ApiResponse<?> register(@RequestBody RegisterRequest request) {
        return authService.register(request);
    }

    @PostMapping("/login")
    public ApiResponse<?> login(@RequestBody RegisterRequest request) {
        return authService.login(request);
    }

    @PostMapping("/logout")
    public ApiResponse<?> logout(
            Authentication authentication,
            @RequestHeader(value = "Authorization", required = false) String authHeader,
            @RequestHeader(value = "X-Token", required = false) String xToken
    ) {
        String token = null;
        if (authHeader != null && authHeader.startsWith("Bearer ")) {
            token = authHeader.substring(7);
        } else if (xToken != null) {
            token = xToken;
        }

        if (token != null) {
            tokenBlacklistService.addToBlacklist(token);
            return ApiResponse.success("退出登录成功");
        }
        
        return ApiResponse.error("无效的token");
    }
} 